/* 
 * The MIT License
 *
 * Copyright 2014 Venkat Ram Akkineni.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package org.netbeans.modules.tfsnb.core.multiview;

import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.Action;
import javax.swing.JLayeredPane;
import org.netbeans.modules.tfsnb.core.tabs.TFSConnectionExplorerTopComponent;
import org.openide.cookies.InstanceCookie;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
import org.openide.windows.TopComponent;
import org.reflections.Reflections;

/**
 *
 * @author Venkat Ram Akkineni
 */
@Deprecated
public class MultiViewManager implements MultiViewPanelCallback {
    
    private Map<String, MultiViewPanel> views;
    private Map<String, SwitchViewToggleButton> switchViewButtons;
    private final TopComponent topComponent;
        
    private static final Logger LOG = Logger.getLogger(MultiViewManager.class.getName());  
    private String topComponentId;
    private Reflections reflections;
    

    public MultiViewManager(final TopComponent topComponent) throws Exception {
        this.topComponent = topComponent;
        Annotation[] topComponentAnnotations = topComponent.getClass().getAnnotations();
        for(Annotation annotation: topComponentAnnotations) {
            if(annotation.annotationType().equals(TopComponent.Description.class)) {
                this.topComponentId = ((TopComponent.Description) annotation).preferredID();
            }
        }
        lookupMultiviews();
        if(topComponentId == null) throw new Exception("TopComponent should have a preferredId. Look at TopComponent.Description annotation.");
    }
    
    private void lookupViews() {         
        Set<Class<?>> annotated = reflections.getTypesAnnotatedWith(MultiViewPanelRegistration.class);
        views = new HashMap<>();
        for(Class clazz: annotated) {
            try {
                MultiViewPanel panel = (MultiViewPanel) clazz.newInstance();                
                MultiViewPanelRegistration regAnn = (MultiViewPanelRegistration) clazz.getAnnotation(MultiViewPanelRegistration.class);
                if(regAnn != null) {
                    panel.setId(topComponentId + "_" + regAnn.id());
                    panel.setMultiViewPanelDescription(new MultiViewPanelDescription(regAnn));
                    panel.setLookup(topComponent.getLookup());
                    panel.setMultiViewCallback(this);
                    views.put(panel.getId(), panel);                
                }
            } catch (InstantiationException | IllegalAccessException ex) {
                LOG.log(Level.SEVERE, ex.getMessage());
            }
        }
    }
    
    private void lookupMultiviews() throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException {
        if(views == null ) views = new HashMap<>();
        FileObject fileObject = FileUtil.getConfigRoot();
        FileObject explorer = fileObject.getFileObject("TFS/Explorer/MultiView");
        FileObject[] multiViews = explorer.getChildren();        
                
        for(FileObject multiView: multiViews) {
            String className = (String) multiView.getAttribute("instance");
            String displayName = (String) multiView.getAttribute("displayName");
            String iconBase = (String) multiView.getAttribute("iconBase");
            String id = (String) multiView.getAttribute("id");
            String topComponentPreferredId = (String) multiView.getAttribute("topComponentPreferredId");
            int position = (int) multiView.getAttribute("position");
            
            MultiViewPanelDescription multiViewDescription = new MultiViewPanelDescription(displayName, iconBase, id, topComponentPreferredId, position);      
            InstanceCookie cookie = multiView.getLookup().lookup(InstanceCookie.class);
            MultiViewPanel multiViewPanel = (MultiViewPanel) cookie.instanceCreate();
            
            multiViewPanel.setId(topComponentId + "_" + multiViewDescription.getId());
            multiViewPanel.setMultiViewPanelDescription(multiViewDescription);
            multiViewPanel.setLookup(topComponent.getLookup());
            multiViewPanel.setMultiViewCallback(this);            
            views.put(multiViewPanel.getId(), multiViewPanel);
        }
    }
    
    /**
     * Looks up switchView Toggle Buttons.
     */
    private void lookupSwitchViewButtons() {
        if(views == null || views.isEmpty()) {            
            try {            
                lookupMultiviews();
            } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | IOException ex) {
                LOG.log(Level.SEVERE,  ex.getMessage());
            } 
        }
        HashMap<String, SwitchViewToggleButton> viewButtons = new HashMap<>();
        for(MultiViewPanel view: views.values()) {
            MultiViewPanelDescription viewDesc = view.getMultiViewPanelDescription();            
            if(topComponentId.equals(viewDesc.getTopComponentPreferredId())) {
                final SwitchViewToggleButton button = new SwitchViewToggleButton(viewDesc, topComponentId, this);
                viewButtons.put(button.getId(), button);
            }
        }
        
        SwitchViewToggleButton.ButtonComparator comparator = new SwitchViewToggleButton.ButtonComparator(viewButtons);
        switchViewButtons = new TreeMap<>(comparator); // Sorted Map     
        switchViewButtons.putAll(viewButtons);
    }
    
    public MultiViewPanel getMultiViewPanel(final String buttonId) {
        if(views == null) {
            try {
                lookupMultiviews();
            } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | IOException ex) {
                LOG.log(Level.SEVERE,  ex.getMessage());
            }
        }
        if(switchViewButtons == null) lookupSwitchViewButtons();
        
        String panelId = buttonId.substring(0, buttonId.indexOf(SwitchViewToggleButton.BUTTON_ID_SUFFIX) - 1);
        return views.get(panelId);
    }
    
    /**
     * 
     * @param reload a {boolean} value indicating whether to force reload.
     * @return 
     */
    public Map<String, MultiViewPanel> getViews(final boolean reload) {
        if(views == null || views.isEmpty() || reload) {
            try {
                lookupMultiviews();
            } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | IOException ex) {
                LOG.log(Level.SEVERE,  ex.getMessage());
            }
        }
        return views;
    }
    
    /**
     * 
     * @param reload a {boolean} value indicating whether to force reload.
     * @return 
     */
    public Map<String, SwitchViewToggleButton> getSwitchViewButtons(final boolean reload) {
        if(switchViewButtons == null || switchViewButtons.isEmpty() || reload) {
            lookupSwitchViewButtons();
        }
        return switchViewButtons;
    }
    
    public void switchPanel(String buttonId) {        
//        JLayeredPane lp = ((TFSConnectionExplorerTopComponent) topComponent).getBodyLayeredPane();
//        lp.moveToFront(getMultiViewPanel(buttonId).getVisualRepresentation());
        //TODO: switch toolbar
    }
    
    public void showFirstPanel() {
        if(switchViewButtons != null) {            
            if(switchViewButtons.size() > 0) {
//                ((SwitchViewToggleButton[]) switchViewButtons.values().toArray());
//                switchViewButtons.get(switchViewButtons.firstKey()).setSelected(true);
                SwitchViewToggleButton but = switchViewButtons.values().iterator().next();
                but.setSelected(true);
                switchPanel(but.getId());
            }
        }  else LOG.log(Level.INFO, "No Multi Views defined, nothing to show.");
    }
    
    public void hideAllPanels() {
        for(MultiViewPanel view: views.values()) {
            view.getVisualRepresentation().setVisible(false);
        }
    }
    
    /**
     *
     * @param multiView     
     */
    public static void createMultiViewPanel(final FileObject multiView) {
        String displayName = (String) multiView.getAttribute("displayName");
        String iconBase = (String) multiView.getAttribute("iconBase");
        String id = (String) multiView.getAttribute("id");
        String topComponentPreferredId = (String) multiView.getAttribute("topComponentPreferredId");            
        int position = Integer.parseInt((String) multiView.getAttribute("position"));

        MultiViewPanelDescription multiViewDescription = new MultiViewPanelDescription(displayName, iconBase, id, topComponentPreferredId, position);          
    }
    
    // start: MultiViewPanelCallback
    @Override
    public Action[] createDefaultActions() {
        return new Action[0];
    }

    @Override
    public void updateTitle(String title) {
        topComponent.setDisplayName(title);
    }

    @Override
    public boolean isSelectedElement() {
        return true;
    }

    @Override
    public TopComponent getTopComponent() {
        return topComponent;
    }   

    @Override
    public void requestActive() {
        
    }

    @Override
    public void requestVisible() {
        
    }
    // end: MultiViewPanelCallback
}
